package com.muchen.partnermatching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.muchen.partnermatching.common.ErrorCode;
import com.muchen.partnermatching.constant.RedisConstant;
import com.muchen.partnermatching.constant.UserConstant;
import com.muchen.partnermatching.enums.HttpStatusEnum;
import com.muchen.partnermatching.exception.BusinessException;
import com.muchen.partnermatching.model.domain.User;
import com.muchen.partnermatching.model.vo.R;
import com.muchen.partnermatching.model.vo.TagVo;
import com.muchen.partnermatching.service.UserService;
import com.muchen.partnermatching.mapper.UserMapper;
import com.muchen.partnermatching.utils.AlgorithmUtils;
import com.muchen.partnermatching.utils.StringUtil;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.muchen.partnermatching.constant.UserConstant.SALT;
import static com.muchen.partnermatching.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 14535
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-09-23 00:27:22
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    private static final Integer ADMIN_ROLE = 1;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplateSS;

    @Autowired
    private RedisTemplate<String, Object> redisTemplateSO;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,
                             String username, String email, String checkCode) {
        // 1. 校验
        // 获取正确的验证码
        String rightCode = redisTemplateSS.opsForValue().get(RedisConstant.EMAIL + email);
        if (!checkCode.equals(rightCode)) {
            // 验证码比对
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }

        // 用户名或密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, username, email, checkCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 账号是否小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        // 密码不小于八位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        // 邮箱格式校验
        if (!StringUtil.checkEmail(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }

        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码与校验密码不相同");
        }
//        // 星球编号大于5位
//        if (planetCode.length() < 6) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过短");
//        }
        // 账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 账号不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }

        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该邮箱已被注册");
        }
        // 星球编号不能重复
//        queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("planetCode", planetCode);
//        count = userMapper.selectCount(queryWrapper);
//        if (count > 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
//        }

        // 删除验证码
        redisTemplateSS.delete(RedisConstant.EMAIL + email);

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + checkPassword).getBytes());

        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUsername(username);
        user.setEmail(email);
        user.setAvatarUrl("https://img2.baidu.com/it/u=1926236373,3002779851&fm=253&fmt=auto?w=800&h=801");
//        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        // 用户名或密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        // 账号是否小于4位
        if (userAccount.length() < 4) {
            return null;
        }
        // 密码不小于八位
        if (userPassword.length() < 8) {
            return null;
        }
        // 账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());


        // 查询该用户是否存在，密码是否正确
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }

        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);

        // 4. 记录用户的登录状态
        String redisKey = String.format(USER_LOGIN_STATE + safetyUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplateSO.opsForValue();
        valueOperations.set(redisKey, safetyUser, 30, TimeUnit.MINUTES);
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setProfile(originUser.getProfile());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public Boolean userLogout(String id, HttpServletRequest request) {
        // 移除登录态
        String redisKey = String.format(USER_LOGIN_STATE + id);
        log.info(redisKey);
        Boolean delete = redisTemplateSO.delete(redisKey);
        return delete;
    }

    /**
     * 根据标签搜索用户。(内存过滤版)
     *
     * @param tagNameList 用户要搜索的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1.先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("tags","[]");
        queryWrapper.isNotNull("tags");
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //2.判断内存中是否包含要求的标签 parallelStream()
        return userList.stream().filter(user -> {
            String tagstr = user.getTags();
//            if (StringUtils.isBlank(tagstr)){
//                return false;
//            }
            Set<String> tempTagNameSet = gson.fromJson(tagstr, new TypeToken<Set<String>>() {
            }.getType());
            //java8  Optional 来判断空
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());

            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 校验权限
        // 2.1 管理员可以更新任意信息、用户只能更新自己的信息
        if (!isAdmin(loginUser) && !userId.equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        // 3. 触发更新
        return userMapper.updateById(user);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != UserConstant.ADMIN_ROLE) {
            return false;
        }
        return true;
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @Override
    public User getCurrentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return user;
    }


    /**
     * 根据标签搜索用户。(sql查询版)
     *
     * @param tagNameList 用户要搜索的标签
     * @return
     * @Deprecated 过时
     */
    @Deprecated
    private List<User> searchUsersByTagBySQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //拼接tag
        // like '%Java%' and like '%Python%'
        for (String tagList : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagList);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public List<User> matchUsers(long num, User currentUser) {
        // 创建一个QueryWrapper对象，用于查询User表
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询id和tags字段
        queryWrapper.select("id", "tags");
        // 获取当前用户的tags
        String tags = currentUser.getTags();
        if (tags == null || "[]".equals(tags)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "用户标签为空");
        }
        // 查询tags字段不为null或空的记录
        queryWrapper.ne("tags", "[]");
        queryWrapper.isNotNull("tags");
        // 查询出所有符合条件的用户
        List<User> userList = this.list(queryWrapper);
        // 创建一个Gson对象
        Gson gson = new Gson();
        // 将当前用户的tags转换为List<String>类型
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        Collections.sort(tagList);
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            // 获取用户的tags
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || user.getId().equals(currentUser.getId())) {
                continue;
            }
            // 将用户的tags转换为List<String>类型
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            Collections.sort(userTagList);
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            // 将用户和相似度添加到list中
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        // 创建一个QueryWrapper对象，用于查询User表
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 查询id在userIdList中的记录
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        // 查询出所有符合条件的用户，并按id分组
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        // 创建一个List<User>对象，用于存储最终结果
        List<User> finalUserList = new ArrayList<>();
        // 遍历userIdList，将对应的用户添加到finalUserList中
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        // 返回最终结果
        return finalUserList;
    }

    @Override
    public long userReSetPwd(String userAccount, String userPassword, String checkPassword, String email, String checkCode) {
        // 1. 校验
        // 获取正确的验证码
        String rightCode = redisTemplateSS.opsForValue().get(RedisConstant.EMAIL + email);
        if (!checkCode.equals(rightCode)) {
            // 验证码比对
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        // 删除验证码
        redisTemplateSS.delete(RedisConstant.EMAIL + email);

        // 用户名或密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, email, checkCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        // 密码不小于八位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        // 邮箱格式校验
        if (!StringUtil.checkEmail(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }

        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码与校验密码不相同");
        }
//        // 星球编号大于5位
//        if (planetCode.length() < 6) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过短");
//        }

        // 构造查询条件对象
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 查询userAccount和email字段
        wrapper.select("id", "userAccount", "email");
        // email与账号必须与查询结果一致
        wrapper.eq("email", email);
        wrapper.eq("userAccount", userAccount);
        // 限制查询结果为一条
        wrapper.last("limit 1");

        // 查询用户，是否存在
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该用户不存在");
        }
        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + checkPassword).getBytes());
        // 修改密码
        user.setUserPassword(encryptPassword);

        // 修改
        return userMapper.updateById(user);
    }

    @Override
    public TagVo getTags(String id, HttpServletRequest request) {
        // 判断request是否为空，如果为空则抛出异常
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建TagVo对象
        TagVo tagVo = new TagVo();
        // 记录id
        log.info("id:" + id);
        // 构造redisKey
        String redisKey = String.format(USER_LOGIN_STATE + id);
        // 获取redisTemplate的ValueOperations对象
        ValueOperations<String, Object> valueOperations = redisTemplateSO.opsForValue();
        // 从redis中获取当前用户
        User currentUser = (User) valueOperations.get(redisKey);
        // 根据当前用户id获取用户信息
        User userById = this.getById(id);
        // 获取当前用户的tags
        String OldTags = userById.getTags();
        // 构造QueryWrapper对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询tags不为空的用户
        queryWrapper.isNotNull("tags");
        queryWrapper.ne("tags", "[]");
        // 查询所有tags不为空的用户
        List<User> users = this.list(queryWrapper);
        // 创建map对象，用于存储tags和对应的数量
        Map<String, Integer> map = new HashMap<>();
        // 创建Gson对象
        Gson gson = new Gson();
        // 记录OldTags
        log.info(OldTags);
        // 将OldTags转换为List<String>
        List<String> oldTags = gson.fromJson(OldTags, new TypeToken<List<String>>() {
        }.getType());
        // 记录oldTags
        log.info(oldTags.toString() + "");
        // 遍历所有用户
        for (User user : users) {
            // 获取用户的tags
            String Tags = user.getTags();
            // 将Tags转换为List<String>
            List<String> list = Arrays.asList(Tags);
            // 如果list为空，则跳过
            if (list == null) {
                continue;
            }
            // 将Tags转换为List<String>
            List<String> tagList = gson.fromJson(Tags, new TypeToken<List<String>>() {
            }.getType());
            // 如果tagList不为空，则遍历tagList
            if (tagList != null) {
                for (String tag : tagList) {
                    // 如果map中不存在tag，则将tag和数量1存入map
                    if (map.get(tag) == null) {
                        map.put(tag, 1);
                    } else {
                        // 如果map中存在tag，则将tag的数量加1
                        map.put(tag, map.get(tag) + 1);
                    }
                }
            }
        }
        // 创建TreeMap对象，用于存储数量和对应的tags
        Map<Integer, List<String>> Map = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer key1, Integer key2) {
                // 降序排序
                return key2.compareTo(key1);
            }
        });
        // 遍历map
        map.forEach((value, key) -> {
            // 如果Map的大小为0，则将value和key存入Map
            if (Map.size() == 0) {
                Map.put(key, Arrays.asList(value));
            } else if (Map.get(key) == null) {
                // 如果Map中不存在key，则将value和key存入Map
                Map.put(key, Arrays.asList(value));
            } else {
                // 如果Map中存在key，则将value添加到Map中对应的List中
                List<String> list = new ArrayList(Map.get(key));
                list.add(value);
                Map.put(key, list);
            }
        });
        // 创建set对象，用于存储推荐tags
        Set<String> set = new HashSet<>();
        // 遍历Map
        for (Map.Entry<Integer, List<String>> entry : Map.entrySet()) {
            // 记录set的大小
            log.info("set.size():"+set.size());
            // 获取Map中的value
            List<String> value = entry.getValue();
            // 如果oldTags为空，则将value中的所有tag添加到set中
            if (oldTags == null) {
                for (String tag : value) {
                    set.add(tag);
                    // 如果set的大小大于等于20，则跳出循环
                    if (set.size() >= 20) {
                        break;
                    }
                }
            }
            // 遍历value
            for (String tag : value) {
                // 如果oldTags中不包含tag，则将tag添加到set中
                if (!oldTags.contains(tag)) {
                    set.add(tag);
                    // 如果set的大小大于等于20，则跳出循环
                    if (set.size() >= 20) {
                        break;
                    }
                }
            }
        }
        // 将set转换为List<String>
        List<String> RecommendTags = new ArrayList<String>(set);
        // 记录RecommendTags
        log.info("RecommendTags:"+RecommendTags);
        // 将oldTags和RecommendTags存入tagVo
        tagVo.setOldTags(oldTags);
        tagVo.setRecommendTags(RecommendTags);
        // 返回tagVo
        return tagVo;
    }
}




